/**
 * 
 */
package com.ruyipu.forum.base;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ruyipu.forum.interfaces.IItem;

/**
 * @author donald
 * 
 */
public final class Factory {

	public static final String TAG = Factory.class.getSimpleName();
	public static final String NAME = Factory.class.getName();

	private Factory() {
	}

	/**
	 * 从JSONObject中获取
	 * 
	 * @param jsonObject
	 * @param className
	 * @return
	 */
	public static IItem factoryItem(JSONObject jsonObject, String className) {
		IItem item = null;
		if (null != jsonObject && null != className && !"".equals(className)) {

			Object myObject = null;
			try {
				Class<?> myClass = Class.forName(className);
				myObject = myClass.newInstance();
			} catch (ClassNotFoundException e) {
				MyLog.e(TAG, e);
				return null;
			} catch (IllegalAccessException e) {
				MyLog.e(TAG, e);
				return null;
			} catch (InstantiationException e) {
				MyLog.e(TAG, e);
				return null;
			}

			if (myObject != null) {
				item = (IItem) myObject;
				try {
					item.parse(jsonObject);
				} catch (JSONException e) {
					MyLog.e(TAG, e);
					return null;
				}
			}
		}
		return item;
	}

	public static List<IItem> factoryItemList(JSONArray jsonArray, String type) {
		List<IItem> dataList = new ArrayList<IItem>();
		if (null != jsonArray || null != type) {
			for (int i = 0; i < jsonArray.length(); i++) {
				IItem item = factoryItem(jsonArray.optJSONObject(i), type);
				if (null != item) {
					dataList.add(item);
				}
			}
		}
		return dataList;
	}

	public static List<IItem> factoryItemList(JSONObject jsonObject, String type) {
		List<IItem> dataList = new ArrayList<IItem>();
		if (null != jsonObject || null != type) {
			JSONArray jsonArray = jsonObject.optJSONArray(Constants.DATA);
			if (null != jsonArray) {
				dataList = factoryItemList(jsonArray, type);
			}
		}
		return dataList;
	};
}
